package com.cdks.wuxiu.api.component.huawei;


import java.util.ArrayList;
import java.util.List;

import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.moderation.v3.region.ModerationRegion;

import cn.hutool.json.JSONUtil;

import com.huaweicloud.sdk.moderation.v3.*;
import com.huaweicloud.sdk.moderation.v3.model.*;
import com.huaweicloud.sdk.moderation.v3.model.AudioModerationResultResult.SuggestionEnum;
import com.huaweicloud.sdk.moderation.v3.model.RunQueryAudioModerationJobResponse.StatusEnum;

import lombok.extern.slf4j.Slf4j;


@Slf4j
public class Moderation
{
    public static int checkText(String content) {
        return checkText(content, null);
    }

    public static int checkText(String inText, StringBuilder outText) {
        if ((inText == null) || (inText.isEmpty()))
        {
            return 0;
        }

        ICredential auth = new BasicCredentials()
                .withAk(Config.ak)
                .withSk(Config.sk);

        ModerationClient client = ModerationClient.newBuilder()
                .withCredential(auth)
                .withRegion(ModerationRegion.valueOf("cn-north-4"))  //把xxx替换成服务所在的区域，例如北京四：cn-north-4。
                .build();

        TextDetectionDataReq databody = new TextDetectionDataReq();
        
        //去掉所有英文标点符号、换行符、空格和中文冒号
        String regex = "[\\p{Punct}\\r\\n\\s：]";
        String content  = inText.replaceAll(regex, "");
        //为了增加私加联系方式的灵敏度，在只包含英文和数字的内容前面增加一个加号
        if (content.matches("[a-zA-Z0-9]+"))
        {
            databody.withText("+" + content);
        }
        else
        {
            databody.withText(content);
        }

        TextDetectionReq body = new TextDetectionReq();
        body.withData(databody);
        body.withEventType("nickname");

        RunTextModerationRequest request = new RunTextModerationRequest();
        request.withBody(body);

        try {
            RunTextModerationResponse response = client.runTextModeration(request);
            TextDetectionResult result  = response.getResult();
                
            log.info("Moderation: " + result);
            log.info("Moderation: " + content);

            if (result.getSuggestion().equals("pass"))
            {
                return 0;
            }

            content  = inText;
            boolean finish  = false;
            if (outText != null)
            {
                List<TextDetectionResultDetail> details  = result.getDetails();
                for (TextDetectionResultDetail detail : details)
                {
                    List<SegmentResult> segments  = detail.getSegments();
                    if (segments.isEmpty())
                    {
                        content  = "***";

                        break;                        
                    }

                    for (SegmentResult segment : segments)
                    {
                        String word  = segment.getSegment();
                        if (word.isEmpty() || word.equals(""))
                        {
                            finish   = true;
                            content  = "***";

                            break;
                        }
                        else
                        {
                            String replace  = content.replace(word, "***");
                            if (replace.equals(content))
                            {
                                finish   = true;
                                content  = "***";

                                break;
                            }
                            else
                            {
                                content  = replace;
                            }
                        }
                    }

                    if (finish)
                    {
                        break;
                    }
                }

                outText.append(content);
            }

            if (result.getLabel().equals("porn"))
            {
                return -14;
            }
            if (result.getLabel().equals("abuse"))
            {
                return -13;
            }
            if (result.getLabel().equals("ad"))
            {
                return -12;
            }
            else
            {
                return -11;
            }
        } catch (Exception e) {
            log.error("text: " + inText);
            log.error(e.getMessage());
        }

        return -10;
    }

    public static int checkImage(String fileUrl) {
        ICredential auth = new BasicCredentials()
                .withAk(Config.ak)
                .withSk(Config.sk);

        ModerationClient client = ModerationClient.newBuilder()
                .withCredential(auth)
                .withRegion(ModerationRegion.valueOf("cn-north-4"))
                .build();

        List<String> listbodyCategories = new ArrayList<>();
        listbodyCategories.add("image_text");
        listbodyCategories.add("terrorism");
        listbodyCategories.add("porn");

        ImageDetectionReq body = new ImageDetectionReq();
        body.withUrl(Config.baseUrl + fileUrl);
        body.withCategories(listbodyCategories);
        body.withEventType("comment");

        CheckImageModerationRequest request = new CheckImageModerationRequest();
        request.withBody(body);
        try {
            CheckImageModerationResponse response = client.checkImageModeration(request);
            ImageDetectionResult result  = response.getResult();

            log.info("Moderation: " + JSONUtil.toJsonStr(result));
            
            if (result.getSuggestion().equals("pass"))
            {
                return 0;
            }

            if (result.getCategory().equals("porn"))
            {
                return -14;
            }
            if (result.getCategory().equals("image_text"))
            {
                return -12;
            }
            else
            {
                log.info("Moderation: " + JSONUtil.toJsonStr(result));
    
                return -11;
            }
        } catch (Exception e) {
            log.error("image: " + fileUrl);
            log.error(e.getMessage());
        }

        return -10;
    }

    public static int checkAudio(String fileUrl)
    {
        ICredential auth = new BasicCredentials()
                .withAk(Config.ak)
                .withSk(Config.sk);

        ModerationClient client = ModerationClient.newBuilder()
                .withCredential(auth)
                .withRegion(ModerationRegion.valueOf("cn-north-4"))
                .build();

        RunCreateAudioModerationJobRequest request = new RunCreateAudioModerationJobRequest();
        AudioCreateRequest body = new AudioCreateRequest();
        List<AudioCreateRequest.CategoriesEnum> listbodyCategories = new ArrayList<>();
        listbodyCategories.add(AudioCreateRequest.CategoriesEnum.fromValue("politics"));
        listbodyCategories.add(AudioCreateRequest.CategoriesEnum.fromValue("porn"));
        listbodyCategories.add(AudioCreateRequest.CategoriesEnum.fromValue("ad"));
        listbodyCategories.add(AudioCreateRequest.CategoriesEnum.fromValue("moan"));
        listbodyCategories.add(AudioCreateRequest.CategoriesEnum.fromValue("abuse"));

        AudioInputBody databody = new AudioInputBody();
        databody.withUrl(Config.baseUrl + fileUrl);
        body.withCategories(listbodyCategories);
        body.withEventType(AudioCreateRequest.EventTypeEnum.fromValue("private"));
        body.withData(databody);
        request.withBody(body);

        try {
            RunCreateAudioModerationJobResponse response = client.runCreateAudioModerationJob(request);
            String jobId  = response.getJobId();
            if (jobId != null)
            {
                AudioModerationResultResult result;
                RunQueryAudioModerationJobResponse resultResponse;
                RunQueryAudioModerationJobRequest resultRequest = new RunQueryAudioModerationJobRequest();
                resultRequest.withJobId(jobId);

                do
                {
                    Thread.sleep(100);
                    resultResponse = client.runQueryAudioModerationJob(resultRequest);
                } while(resultResponse.getStatus() == StatusEnum.RUNNING);

                log.info("Moderation: " + JSONUtil.toJsonStr(resultResponse));

                result  = resultResponse.getResult();
                if (result == null)
                {
                    return -10;
                }

                if (result.getSuggestion() == SuggestionEnum.PASS)
                {
                    return 0;
                }

                List<AudioModerationResultDetail> details  = result.getDetails();
                for (AudioModerationResultDetail detail : details)
                {
                    if (detail.getLabel().equals("porn"))
                    {
                        return -14;
                    }
                    if (detail.getLabel().equals("abuse"))
                    {
                        return -13;
                    }                       
                    if (detail.getLabel().equals("ad"))
                    {
                        return -12;
                    }
                    else
                    {
                        return -11;
                    }
                }
            }
        } catch (Exception e) {
            log.error("audio: " + fileUrl);
            log.error(e.getMessage());
        }

        return -10;
    }
}
